package com.zhenxiang.juc.assist;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @Author : James
 * @Create : 2021-12-22-12:00
 * @Description :  栅栏类 多个线程达到同一状态 ，打破栅栏前 执行一个线程任务
 *  解析：https://blog.csdn.net/qq_39241239/article/details/87030142
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {

        /**
         *  parties=7 是线程个数
         *  Runnable 是共同打破栅栏前需要执行的任务
         *
         */
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println("召唤七颗龙珠成功！");
        });


        for (int i = 1; i <= 7; i++) {
            final int temp =i;
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"搜集第"+temp+"龙珠");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                if (cyclicBarrier.isBroken()){
                    Thread.interrupted();
                }
            }).start();
        }


    }
}
